import re
from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from rest_framework_jwt.settings import api_settings
from drf_haystack.serializers import HaystackSerializer

from goods.models import SKU
from users import constants
from .models import User, Address
from celery_tasks.email.tasks import send_verify_email


class UserModelSerializer(ModelSerializer):
    password2 = serializers.CharField(label='确认密码', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)
    token = serializers.CharField(label='登陆状态token', read_only=True)

    class Meta:
        model = User
        # 序列化中要用到的所有字段: 'id', 'username', 'password', 'password2', 'mobile', 'sms_code', 'allow'
        # 模型中存在的字段:  id, username, password, mobile
        # 输出字段: id, username, mobile
        # 输入字段  'username', 'password', 'password2', 'mobile', 'sms_code', 'allow'
        fields = ['id', 'username', 'password', 'password2', 'mobile', 'sms_code', 'allow', "token"]
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validate_mobile(self, value):
        """验证手机号"""
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def validate_allow(self, value):
        """检验用户是否同意协议"""
        if value != 'true':
            raise serializers.ValidationError('请同意用户协议')
        return value

    def validate(self, data):
        # 判断两次密码
        if data['password'] != data['password2']:
            raise serializers.ValidationError('两次密码不一致')

        # 判断短信验证码
        redis_conn = get_redis_connection('verify_code')
        mobile = data['mobile']
        real_sms_code = redis_conn.get('sms_%s' % mobile)
        if real_sms_code is None:
            raise serializers.ValidationError('无效的短信验证码')
        if data['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')

        return data

    # def create(self, validated_data):
    #     # 重写序列化器的存储方法,把password2 sms_code allow数据从validated_data字典中移除
    #     validated_data.pop('password2')
    #     validated_data.pop('sms_code')
    #     validated_data.pop('allow')
    #
    #     # user = User.objects.create(**validated_data)
    #     user = User(**validated_data) # 创建user模型对象
    #     user.set_password(validated_data['password'])  # 对要存储的密码进行加密处理
    #     user.save()  # 存储用户数据到数据中
    #     # user = super(UserModelSerializer, self).create(validated_data)
    #     return user

    def create(self, validated_data):
        # 重写序列化器的存储方法， 把password2， sms_code allow数据从validate字典中移除

        validated_data.pop('password2')
        validated_data.pop('sms_code')
        validated_data.pop('allow')

        user = User(**validated_data)  # 创建user模型对象
        # 调用django的认证系统加密密码
        user.set_password(validated_data['password'])  # 对要存储的密码进行加密处理
        # 补充生成记录登录状态的token

        # 加载生成jwt配置中的处理payload的函数
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        # 加载生成token的函数
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        # 传入用户对象生成payload
        payload = jwt_payload_handler(user)
        #
        token = jwt_encode_handler(payload)
        user.token = token
        user.save()

        return user


class UserDetailSerializer(serializers.ModelSerializer):
    """
    用户详细信息序列化器
    """

    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'email', 'email_active']


class EmailSerializer(serializers.ModelSerializer):
    """邮箱序列化器"""

    class Meta:
        model = User
        fields = ['id', 'email']
        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    def update(self, instance, validated_data):
        """
        因为要修改或者更新，因为数据库已经已近存在email的空字段
        其实ModelSerializer已经实现了update方法
        重写update方法是为了后面发邮件用的
        因为没有写发邮件的视图，所以借用这个update方法
        ，当email保存玩没问题的时候就可以直接发邮件了
        """
        instance.email = validated_data['email']
        instance.save()
        # 对象，方法调用
        verify_url = instance.generate_verify_email_url()
        send_verify_email.delay(instance.email, verify_url)
        # 发送验证邮件
        return instance


class UserAddressSerializer(serializers.ModelSerializer):
    """
    用户地址序列化器
    """
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def validate_mobile(self, value):
        """
        验证手机号
        """
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        """
        反序列化器里面有两个方法create， update
        因为前面在反序列化字段的时候排除了user
        而在新增的时候又用到user  所以需要重写create方法，增加user字段
        """
        # 在饭序列化器里面有上下文context属性  里面有views  和request
        validated_data['user'] = self.context['request'].user
        # 在饭序列化器里面有上下文
        # return super().create(validated_data)
        return Address.objects.create(**validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ('title',)


class AddUserBrowsingHistorySerializer(serializers.Serializer):
    """添加用户浏览历史序列化器"""

    sku_id = serializers.IntegerField(label='商品SKU编号')

    def validate_sku_id(self, value):
        """
        检验sku_id是否存在
        """
        try:
            SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('该商品不存在')
        return value

    def create(self, validated_data):
        """
        重写create方法保存数据到redis数据库
        因为默认配置是保存到mysql数据库
        """
        user_id = self.context['request'].user.id
        sku_id = validated_data['sku_id']

        # 创建redis数据库对象
        redis_conn = get_redis_connection('history')
        pl = redis_conn.pipeline()

        # 去重
        pl.lrem('history_%s' % user_id, 0, sku_id)  # 0 表示把全部重复的都删掉
        # 添加新的浏览记录  从左往右加
        pl.lpush('history_%s' % user_id, sku_id)
        # 只保存最多五条记录
        pl.ltrim('history_%s' % user_id, 0, constants.USER_BROWSING_HISTORY_COUNTS_LIMIT)  # 后面表示截取的范围
        pl.execute()
        return validated_data



